import styles from "./index.module.scss";
import React, { useEffect, useState } from "react";
import Back from "@/shared/back";
import Icon from "@/components/icon";
import { useDispatch, useSelector } from "react-redux";
import { clearSuggestion, getSuggestion } from "@/store/actions/search";
import { RootState } from "@/types/store";
import { useHistory } from "react-router-dom";
export default function Search() {
  // 分发actions的钩子函数
  const dispatch = useDispatch();
  // 路由跳转钩子
  const history = useHistory();
  let timer: NodeJS.Timeout | null = null;
  // 拿到后台返回的数据
  const { suggestion } = useSelector((state: any) => state.search);
  // 创建存储历史记录的状态
  const [searchHistory, setSearchHistory] = useState<string[]>([]);
  // 组件挂载完 执行一次
  useEffect(() => {
    const histories = JSON.parse(
      localStorage.getItem(GEEK_SEARCH_KEY) ?? "[]"
    ) as string[];

    setSearchHistory(histories);
  }, []);
  // 调用dispatch发请求 搜索数据
  const debouncedDispatch = (value: string) => {
    if (!value) return dispatch(clearSuggestion());
    dispatch(getSuggestion(value) as any); // 调用您的 Redux action
  };
  // 防抖函数  在一段时间内 重复触发事件 只执行最后一次
  const onSearchChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const { value } = event.target;
    // 如果存在之前的定时器，清除它
    if (timer) {
      clearTimeout(timer);
    }

    // 创建新的定时器，延迟执行搜索请求
    timer = setTimeout(() => {
      debouncedDispatch(value);
    }, 300); // 300ms 为延迟时间，可以根据需要调整
  };
  const GEEK_SEARCH_KEY = "GEEK_SEARCH_KEY";
  // 创建搜索历史记录的函数
  const saveHistories = (value: string) => {
    const localHistories = JSON.parse(
      localStorage.getItem(GEEK_SEARCH_KEY) ?? "[]"
    ) as string[];
    let histories = [];

    if (localHistories.length === 0) {
      // 没有
      histories = [value];
    } else {
      // 有
      const exist = localHistories.indexOf(value) >= 0;
      if (exist) {
        // 存在
        const leftHistories = localHistories.filter((item) => item !== value);
        histories = [value, ...leftHistories];
      } else {
        // 不存在
        histories = [value, ...localHistories];
      }
    }

    localStorage.setItem(GEEK_SEARCH_KEY, JSON.stringify(histories));
  };

  // 点击搜索内容，跳转到搜索结果页面
  const onSearch = (item: string) => {
    dispatch(clearSuggestion()); // 清除查询的内容
    saveHistories(item);
    history.push(`/result?q=${item}`);
  };
  // 删除单个搜索记录的回调
  const onDeleteHistory = (value: string) => {
    const newSearchHistory = searchHistory.filter((item) => item !== value); // 删选出关键字 并生成新数组
    setSearchHistory(newSearchHistory); // 重新更新历史记录状态
    localStorage.setItem(GEEK_SEARCH_KEY, JSON.stringify(newSearchHistory)); // 更新本地存储
  };
  // 清空历史记录的回调
  const onClearHistory = () => {
    setSearchHistory([]); // 将历史状态重置为空数组
    localStorage.removeItem(GEEK_SEARCH_KEY); // 清除本地存储中的数据
  };
  return (
    <div className={styles.search_page}>
      <div className={styles.header}>
        <Back />
        <div className={styles.input}>
          <Icon type={"iconbtn_search"} />
          <input
            type="search"
            placeholder={"请输入关键字搜索"}
            onChange={onSearchChange}
          />
        </div>
        <span className={styles.search_btn}>搜索</span>
      </div>
      <ul className={styles.suggest}>
        {suggestion &&
          suggestion.map((item: any, index: string) => {
            return (
              <li key={index} onClick={() => onSearch(item)}>
                <Icon type={"iconbtn_search"} /> <span>{item}</span>
              </li>
            );
          })}
      </ul>
      <ul className={styles.history}>
        <li>
          历史记录
          <Icon type={"iconbtn_del"} onClick={onClearHistory} />
        </li>
        {searchHistory &&
          searchHistory.map((item, index): any => {
            return (
              <li key={index}>
                {item}{" "}
                <Icon
                  type={"iconbtn_essay_close"}
                  onClick={() => onDeleteHistory(item)}
                />
              </li>
            );
          })}
      </ul>
    </div>
  );
}
